// pages/map/map.js
Page({
  data: {
    addmissage: '选的位置',
    stitle: '旅游景区',
    latitude: "24.781441",  // 默认纬度（设备坐标）
    longitude: "118.558863", // 默认经度（设备坐标）
    scale: 14,
    markers: [],            // 地图标记
    circles: [],            // 圆圈
    controls: [{
      id: 1,
      iconPath: '../../images/img/controls.png',
      position: {
        left: 15,
        top: 260 - 50,
        width: 40,
        height: 40
      },
      clickable: true
    }],
    deviceName: '',          // 设备名称
    isOutOfRangeAlerted: false // 标志位：是否已经弹出过“设备不在范围内”的警告
  },

  onLoad: function (options) {
    var that = this;
    // 初始化设备名称为 dev1
    const initialDeviceName = options.deviceName || 'dev1';
    that.setData({
      deviceName: initialDeviceName
    });

    if (options.latitude && options.longitude) {
      that.setData({
        latitude: parseFloat(options.latitude),
        longitude: parseFloat(options.longitude)
      });
      that.addMarker(parseFloat(options.latitude), parseFloat(options.longitude));//新增标记
    }

    wx.getLocation({
      type: 'wgs84',
      success: function (res) {
        that.setData({
          userLatitude: res.latitude,
          userLongitude: res.longitude
        });
        that.initMap();
      },
      fail: function (err) {
        console.error('获取用户地理位置失败：', err);
        wx.showToast({
          title: '获取位置失败',
          icon: 'none'
        });
        that.initMap();
      }
    });
  },

  onShow: function () {
    this.initMap(); // 每次页面显示时重新初始化地图
  },

  initMap() {
    const app = getApp();
    const { latitude, longitude, userLatitude, userLongitude, deviceName, isOutOfRangeAlerted } = this.data;
    const circleRadius = app.getCircleRadius(); // 从全局变量获取最新的范围大小

    // 计算设备与用户之间的距离（单位：米）
    const distance = this.calculateDistance(latitude, longitude, userLatitude, userLongitude);

    // 判断设备是否在范围内
    if (distance > circleRadius && !isOutOfRangeAlerted) {
      wx.showToast({
        title: '设备不在范围内',
        icon: 'none',
        duration: 3000
      });
      this.setData({
        isOutOfRangeAlerted: true // 标记已弹出警告
      });
    } else if (distance <= circleRadius) {
      this.setData({
        isOutOfRangeAlerted: false // 如果设备重新进入范围，重置标志位
      });
    }

    this.setData({
      markers: [{
        id: 0,
        latitude,
        longitude,
        iconPath: '/images/device.png',
        title: deviceName,
        label: {
          content: deviceName,
          fontSize: 12,
          color: '#000000',
          x: 0,
          y: -30,
          textAlign: 'center'
        },
        width: 50,
        height: 50
      }],
      circles: [{
        latitude: userLatitude || latitude,
        longitude: userLongitude || longitude,
        radius: circleRadius,
        color: '#0000FF',
        // fillColor: 'rgba(0, 0, 255, 0.1)',
        fillColor: '#d1fcfeCC', // 填充颜色，半透明
        strokeWidth: 1
      }]
    });
  },

  // 计算两点之间的距离（单位：米）
  calculateDistance(lat1, lon1, lat2, lon2) {
    const R = 6371e3; // 地球半径（单位：米）
    const phi1 = lat1 * Math.PI / 180;
    const phi2 = lat2 * Math.PI / 180;
    const deltaPhi = (lat2 - lat1) * Math.PI / 180;
    const deltaLambda = (lon2 - lon1) * Math.PI / 180;

    const a = Math.sin(deltaPhi / 2) * Math.sin(deltaPhi / 2) +
              Math.cos(phi1) * Math.cos(phi2) *
              Math.sin(deltaLambda / 2) * Math.sin(deltaLambda / 2);
    const c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));

    const distance = R * c; // 单位：米
    return distance;
  },

  bindcontroltap(e) {
    if (e.controlId == 1) {
      this.setData({
        latitude: this.data.latitude,
        longitude: this.data.longitude,
        scale: 14,
      });
    }
  },

  bindmarkertap(e) {
    const markerId = e.markerId;
    const marker = this.data.markers.find(m => m.id === markerId);
    if (marker) {
      wx.showModal({
        title: '设备名称',
        content: `当前设备名称：${marker.title}\n\n点击“确定”返回，点击“修改”进行编辑`,
        showCancel: true,
        cancelText: '修改',
        confirmText: '确定',
        success: (res) => {
          if (res.cancel) {
            wx.showModal({
              title: '修改设备名称',
              editable: true,
              showCancel: true,
              success: (res) => {
                if (res.confirm) {
                  const newDeviceName = res.content || 'dev1'; // 如果为空，则默认为 dev1
                  this.setData({
                    deviceName: newDeviceName,
                    markers: [{
                      ...this.data.markers[0],
                      title: newDeviceName,
                      label: {
                        content: newDeviceName,
                        fontSize: 12,
                        color: '#000000',
                        x: 0,
                        y: -30,
                        textAlign: 'center'
                      }
                    }]
                  });
                  getApp().setDeviceName(newDeviceName); // 保存设备名称
                }
              }
            });
          }
        }
      });
    }
  }
});